#include "transfer.h"
#include <stdio.h>
#include "html_utils.h"

CLIENT * client_create(char * host)
{
  CLIENT * result = clnt_create(host, PAPER_PROG, FIRST_VERS, "tcp");
  if (result == 0) {
    printf("<p> Internal error: Unanable to connect to '%s'.\n", host);
    exit(EXIT_FAILURE);
  }
  return result;
}


void print_papers_row(int id, char * title, char * author)
{
  char num[12];
  char link[100];
  sprintf(link, "<a href=\"paperview.cgi?id=%d\">download</a>", id);
  sprintf(num, "%d.", id);
  table_with_4_columns_row(num, title, author, link);
}

void list(char * host_name)
{
  CLIENT * client = client_create(host_name);
  struct paper_info_t * paper_info;

  int i = 0;
  paper_info = get_paper_1(&i, client);
  if (paper_info->error) {
    printf("<p>No papers at server yet.\n");
    clnt_destroy(client);
    return;
  } 
  table_with_4_columns_header("title", "author(s)");
  print_papers_row(i, paper_info->title, paper_info->author);

  while (paper_info->next_paper_id != -1) {
    i = paper_info->next_paper_id;
    paper_info = get_paper_1(&i, client);
    if (paper_info->error) {
      printf("Internal error: %s\n", paper_info->error_message);
      clnt_destroy(client);
      return;
    }
    print_papers_row(i, paper_info->title, paper_info->author);
  } 
  clnt_destroy(client);
}


void papers_list() 
{
  printf("<h2> Available Papers </h2>");
  list("localhost");
  table_tailer();
}

void add_paper() 
{
  printf("<h2> Add a paper </h2>");
  printf("<form enctype=\"multipart/form-data\" action=\"paperload.cgi\" method=\"POST\">");
  printf("<p>Author(s):<input type=\"text\" name=\"author\">");
  printf("<p>Titile: <input type=\"text\" name=\"title\">");
  printf("<p>File<br/><input type=\"file\" name=\"paper\">");
  printf("<p><input type=\"submit\" value=\"Upload\">");
  printf("</form>");
}

int main()
{
  header("text/html");
  html_header();
  printf("<h1> Papers </h1>");
  papers_list();
  add_paper();
  html_tailer();

  return 0;
}
